package org.erp.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.erp.common.annotation.StockLockBatch;
import org.erp.common.page.PageQueryModel;
import org.erp.product.domain.dto.ConnectToInnerAddDto;
import org.erp.product.domain.dto.InspectionTransferLogQueryDto;
import org.erp.product.domain.entity.ConnectLog;
import org.erp.product.domain.entity.ProductInfo;
import org.erp.product.domain.vo.ProductInfoVo;
import org.erp.product.infrastructure.config.InspectionStateFlow;
import org.erp.product.infrastructure.convert.ConnectConvert;
import org.erp.product.infrastructure.convert.InspectionTransferConvert;
import org.erp.product.infrastructure.enums.InspectionEventEnum;
import org.erp.product.infrastructure.enums.InspectionStatusEnum;
import org.erp.product.infrastructure.enums.SourceChannelEnum;
import org.erp.product.infrastructure.exception.ProductException;
import org.erp.product.infrastructure.mapper.ConnectLogMapper;
import org.erp.product.service.InspectionTransferLogService;
import org.erp.product.service.ProductInfoService;
import org.erp.product.service.TransferLogService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 质检调拨记录服务实现层
 *
 * @author libin
 * @version 1.0
 * @description: 质检调拨记录服务实现层
 * @date 2025/11/13 18:06
 **/
@Log4j2
@Service
@AllArgsConstructor
public class InspectionTransferLogServiceImpl implements InspectionTransferLogService {

    private final InspectionTransferConvert inspectionTransferConvert;

    private final ConnectConvert connectConvert;

    private final ConnectLogMapper connectLogMapper;

    private final ProductInfoService productInfoService;

    private final TransferLogService transferLogService;

    private final RabbitTemplate rabbitTemplate;

    @Override
    public PageQueryModel<ProductInfoVo> pageList(InspectionTransferLogQueryDto inspectionTransferLogQueryDto) {
        return productInfoService.pageList(inspectionTransferConvert.dtoConvertDto(inspectionTransferLogQueryDto));
    }

    @StockLockBatch(listField = "stockIds")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void transfer(ConnectToInnerAddDto connectToInnerAddDto) {
        List<Long> stockIds = connectToInnerAddDto.getStockIds();
        List<ProductInfo> list = searchAndVerify(stockIds, InspectionEventEnum.TRANSFER);
        Integer oldStatus = list.get(0).getInspectionStatus();
        list.forEach(w -> {
            InspectionStatusEnum nextStatus = InspectionStateFlow.next(InspectionStatusEnum.getByCode(w.getInspectionStatus()), InspectionEventEnum.TRANSFER);
            w.setInspectionStatus(nextStatus.getCode());
        });
        Integer newStatus = list.get(0).getInspectionStatus();
        //改状态
        productInfoService.updateBatchById(list);
        // 加操作记录
//        List<TransferLog> transferLogList = TransferLog.getTransferLogList(list, oldStatus, newStatus);
//        transferLogService.saveBatch(transferLogList);
        //创建接驳数据
        List<ConnectLog> connectLogList = list.stream()
                .map(c -> connectConvert.dtoConvert(connectToInnerAddDto, c)).toList();
        connectLogList.forEach(c -> c.setSourceChannel(SourceChannelEnum.INSPECTION.getCode()));
        connectLogMapper.insert(connectLogList);
    }

    @StockLockBatch(directIds = true)
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void returnBack(List<Long> stockIds) {
        List<ProductInfo> list = searchAndVerify(stockIds, InspectionEventEnum.RETURN_BACK);
        Integer oldStatus = list.get(0).getInspectionStatus();
//        list.forEach(w -> {
//            RepairTransferStatusEnum nextStatus = RepairStateFlow.next(RepairTransferStatusEnum.getByCode(w.getRepairStatus()), RepairTransferEventEnum.RETURN_BACK);
//            w.setRepairStatus(nextStatus.getCode());
//        });
//        Integer newStatus = list.get(0).getInspectionStatus();
//        productInfoService.updateBatchById(list);
//        //加操作记录
//        List<TransferLog> transferLogList = TransferLog.getTransferLogList(list, oldStatus, newStatus);
//        transferLogService.saveBatch(transferLogList);
//        // 发起异步消息
//        AsyncMessageStatusDto asyncMessageStatusDto = AsyncMessageStatusDto.buildAsyncMessageStatusDto(list);
//        rabbitTemplate.convertAndSend(RabbitmqConstant.ERP_STORE_EXCHANGE
//                , RabbitmqConstant.ERP_STORE_ROUTING_KEY, JSONObject.toJSONString(asyncMessageStatusDto));
    }

    @Override
    public void onShelf(List<Long> ids) {

    }

    @Override
    public void offShelf(List<Long> ids) {

    }

    public List<ProductInfo> searchAndVerify(List<Long> stockIds, InspectionEventEnum inspectionTransferEventEnum) {
        List<ProductInfo> list = productInfoService.list(new QueryWrapper<ProductInfo>().lambda()
                .in(ProductInfo::getStockId, stockIds));
        for (ProductInfo productInfo : list) {
            try {
                InspectionStateFlow.next(InspectionStatusEnum.getByCode(productInfo.getInspectionStatus()), inspectionTransferEventEnum);
            } catch (Exception e) {
                throw new ProductException("质检调拨id为: " + productInfo.getId() + " 状态不允许执行该操作");
            }
        }
        return list;
    }
}
